<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="物流渠道名称" prop="logisticsName" label-width="120">
              <el-input v-model="queryParams.logisticsInfoName" placeholder="请输入物流渠道名称" clearable />
            </el-form-item>
            <el-form-item label="物流商" prop="logisticsId" label-width="120">
              <provider-select v-model="queryParams.logisticsId" placeholder="请选择物流商" clearable></provider-select>
            </el-form-item>
            <el-form-item label="预计时效天数" prop="expectedShipDays" label-width="120">
              <el-input v-model="queryParams.expectedShipDays" placeholder="请输入预计时效天数" clearable />
            </el-form-item>
            <el-form-item label="传输方式" prop="transportMethod" label-width="120">
              <el-select v-model="queryParams.transportMethod" placeholder="请选择传输方式" clearable>
                <el-option v-for="dict in transport_method" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="目标国家" prop="targetAddress" label-width="120">
              <el-select v-model="queryParams.targetAddress" placeholder="请选择传输方式" clearable>
                <el-option v-for="dict in target_address" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="提货地" prop="pickupAddress" label-width="120">
              <el-select v-model="queryParams.pickupAddress" placeholder="请选择传输方式" clearable>
                <el-option v-for="dict in pickup_address" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否含税" prop="taxFlag" label-width="120">
              <el-select v-model="queryParams.taxFlag" placeholder="请选择是否含税" clearable>
                <el-option v-for="dict in tax_flag" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否分抛计算" prop="splitcalFlag" label-width="120">
              <el-select v-model="queryParams.splitcalFlag" placeholder="请选择是否分抛计算" clearable>
                <el-option v-for="dict in splitcal_flag" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="计费规则" prop="chargeRule" label-width="120">
              <el-select v-model="queryParams.chargeRule" placeholder="请选择计费规则" clearable>
                <el-option v-for="dict in charge_rule" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['logistics:channel:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['logistics:channel:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['logistics:channel:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <!--<el-col :span="1.5">
            <el-button v-hasPermi="['logistics:channel:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="logisticsInfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="" align="center" prop="logisticsInfoId" />
        <el-table-column label="物流渠道名称" align="center" prop="logisticsInfoName" />
        <el-table-column label="物流商名称" align="center" prop="logisticsName" />
        <el-table-column label="预计时效天数" align="center" prop="expectedShipDays" />
        <el-table-column label="传输方式" align="center" prop="transportMethod">
          <template #default="scope">
            {{ transport_method.find((item) => item.value === scope.row.transportMethod)?.label }}
          </template>
        </el-table-column>
        <el-table-column label="目标国家" align="center" prop="targetAddress">
          <template #default="scope">
            {{ target_address.find((item) => item.value === scope.row.targetAddress)?.label }}
          </template>
        </el-table-column>
        <el-table-column label="提货地" align="center" prop="pickupAddress">
          <template #default="scope">
            {{ pickup_address.find((item) => item.value === scope.row.pickupAddress)?.label }}
          </template>
        </el-table-column>
        <el-table-column label="是否含税" align="center" prop="taxFlag">
          <template #default="scope">
            {{ tax_flag.find((item) => item.value === scope.row.taxFlag)?.label }}
          </template>
        </el-table-column>
        <el-table-column label="启用状态" align="center" prop="status">
          <template #default="scope">
            {{ enable_status.find((item) => item.value === scope.row.status)?.label }}
          </template>
        </el-table-column>
        <el-table-column label="计费规则" align="center" prop="chargeRule">
          <template #default="scope">
            {{ charge_rule.find((item) => item.value === scope.row.chargeRule)?.label }}
          </template>
        </el-table-column>
        <el-table-column label="材积参数" align="center" prop="volumnParam" />
        <el-table-column label="是否分抛计算" align="center" prop="splitcalFlag">
          <template #default="scope">
            {{ splitcal_flag.find((item) => item.value === scope.row.splitcalFlag)?.label }}
          </template>
        </el-table-column>
        <el-table-column label="最小重量(kg)" align="center" prop="miniWeight" />

        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <!-- <el-tooltip content="详情" placement="top">
              <el-button link type="primary" @click="handleDetail(scope.row)">详情</el-button>
            </el-tooltip> -->
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['logistics:channel:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['logistics:channel:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改物流渠道对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="1200px" append-to-body>
      <el-form ref="logisticsInfoFormRef" :model="form" :rules="rules" label-width="140px">
        <el-row>
          <el-divider content-position="left">基本信息</el-divider>
          <el-col :span="12">
            <el-form-item label="物流渠道名称" prop="logisticsName">
              <el-input v-model="form.logisticsInfoName" placeholder="请输入物流渠道名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物流商" prop="logisticsId">
              <provider-select v-model="form.logisticsId" v-model:name="form.logisticsName"></provider-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="传输方式" prop="transportMethod">
              <el-select v-model="form.transportMethod" placeholder="请选择传输方式">
                <el-option v-for="dict in transport_method" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="目标国家" prop="targetAddress">
              <el-select v-model="form.targetAddress" placeholder="请输入目标国家">
                <el-option v-for="dict in target_address" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提货地" prop="pickupAddress">
              <el-select v-model="form.pickupAddress" placeholder="请输入提货地">
                <el-option v-for="dict in pickup_address" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计时效天数" prop="expectedShipDays">
              <el-input v-model="form.expectedShipDays" type="number" placeholder="预计时效天数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否含税" prop="taxFlag">
              <el-select v-model="form.taxFlag" placeholder="请选择是否含税">
                <el-option v-for="dict in tax_flag" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="status">
              <el-select v-model="form.status" placeholder="请选择是否启用">
                <el-option v-for="dict in enable_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-divider content-position="left">运费规则</el-divider>
          <el-col :span="12">
            <el-form-item label="计费规则" prop="chargeRule">
              <el-select v-model="form.chargeRule" placeholder="请选择计费规则">
                <el-option v-for="dict in charge_rule" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="材积参数" prop="volumnParam">
              <el-input v-model="form.volumnParam" placeholder="请输入材积参数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否分抛计算" prop="splitcalFlag">
              <el-select v-model="form.splitcalFlag" placeholder="请选择是否分抛计算">
                <el-option v-for="dict in splitcal_flag" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最小重量(kg)" prop="miniWeight">
              <el-input v-model="form.miniWeight" type="number" placeholder="请输入最小重量" />
            </el-form-item>
          </el-col>
          <el-divider />
          <el-col :span="24">
            <el-form-item label="计费规则项" prop="chargeItem">
              <billing-rules v-model="form.chargeItem" v-model:headers="form.chargeItemHeaders" />
            </el-form-item>
          </el-col>
          <el-divider />
          <el-col :span="24">
            <el-form-item label="其他费用" prop="otherChargeItem">
              <OtherBillingRules v-model="form.otherChargeItem" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="LogisticsInfo" lang="ts">
import { pageLogisticsInfo, getLogisticsInfo, delLogisticsInfo, addLogisticsInfo, updateLogisticsInfo } from '@/api/logistics/channel';
import { LogisticsInfoVO, LogisticsInfoQuery, LogisticsInfoForm } from '@/api/logistics/channel/types';
import BillingRules from '@/views/logistics/channel/BillingRules.vue';
import OtherBillingRules from '@/views/logistics/channel/OtherBillingRules.vue';

import ProviderSelect from '@/views/logistics/provider/ProviderSelect.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { transport_method, target_address, pickup_address, tax_flag, enable_status, charge_rule, splitcal_flag } = toRefs<any>(proxy?.useDict('transport_method', 'target_address', 'pickup_address', 'tax_flag', 'enable_status', 'charge_rule', 'splitcal_flag'));

const logisticsInfoList = ref<LogisticsInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const logisticsInfoFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: LogisticsInfoForm = {
  logisticsInfoId: undefined,
  logisticsName: undefined,
  logisticsId: undefined,
  expectedShipDays: undefined,
  transportMethod: undefined,
  targetAddress: undefined,
  pickupAddress: undefined,
  taxFlag: undefined,
  status: undefined,
  chargeRule: undefined,
  volumnParam: undefined,
  splitcalFlag: undefined,
  miniWeight: undefined,
  chargeItem: undefined,
  chargeItemHeaders: undefined,
  otherChargeItem: undefined,
  remark: undefined
};
const data = reactive<PageData<LogisticsInfoForm, LogisticsInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    logisticsName: undefined,
    logisticsId: undefined,
    expectedShipDays: undefined,
    transportMethod: undefined,
    targetAddress: undefined,
    pickupAddress: undefined,
    taxFlag: undefined,
    splitcalFlag: undefined,
    status: undefined,
    miniWeight: undefined,
    volumnParam: undefined,
    chargeRule: undefined,
    chargeItem: undefined,
    params: {}
  },
  rules: {
    logisticsInfoId: [{ required: true, message: '不能为空', trigger: 'blur' }],
    logisticsName: [{ required: true, message: '物流渠道名称不能为空', trigger: 'blur' }],
    logisticsId: [{ required: true, message: '物流商Id不能为空', trigger: 'blur' }],
    validRangeFrom: [{ required: true, message: '时效范围开始不能为空', trigger: 'blur' }],
    validRangeEnd: [{ required: true, message: '时效范围结束不能为空', trigger: 'blur' }],
    transportMethod: [{ required: true, message: '传输方式, 如空运，DHL不能为空', trigger: 'blur' }],
    targetAddress: [{ required: true, message: '目标国家不能为空', trigger: 'blur' }],
    pickupAddress: [{ required: true, message: '提货地不能为空', trigger: 'blur' }],
    taxFlag: [{ required: true, message: '是否含税 1：是   0：否不能为空', trigger: 'blur' }],
    splitcalFlag: [{ required: true, message: '是否分抛计算 1：是   0：否不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态 1：启用 0：禁用不能为空', trigger: 'change' }],
    miniWeight: [{ required: true, message: '最小重量不能为空', trigger: 'blur' }],
    volumnParam: [{ required: true, message: '材积参数不能为空', trigger: 'blur' }],
    chargeRule: [{ required: true, message: '计费规则, 如计费1:重量,2:实重,3:体积不能为空', trigger: 'blur' }],
    chargeItem: [{ required: true, message: '计费规则不能为空', trigger: 'blur' }],
    remark: [{ required: false, message: '备注不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询物流渠道列表 */
const getList = async () => {
  loading.value = true;
  const res = await pageLogisticsInfo(queryParams.value);
  for (let i = 0; i < res.rows.length; i++) {
    if (res.rows[i].chargeItem && res.rows[i].chargeItem.length > 0) {
      res.rows[i].chargeItem = JSON.parse(res.rows[i].chargeItem);
      res.rows[i].chargeItemHeaders = JSON.parse(res.rows[i].chargeItemHeaders);
      res.rows[i].otherChargeItem = JSON.parse(res.rows[i].otherChargeItem);
    }
  }
  logisticsInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  logisticsInfoFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: LogisticsInfoVO[]) => {
  ids.value = selection.map((item) => item.logisticsInfoId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加物流渠道';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: LogisticsInfoVO) => {
  reset();
  const _logisticsInfoId = row?.logisticsInfoId || ids.value[0];
  const res = await getLogisticsInfo(_logisticsInfoId);
  if (res.data.chargeItem && res.data.chargeItem) {
    res.data.chargeItem = JSON.parse(res.data.chargeItem);
    res.data.chargeItemHeaders = JSON.parse(res.data.chargeItemHeaders);
    res.data.otherChargeItem = JSON.parse(res.data.otherChargeItem);
  }
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改物流渠道';
};

/** 提交按钮 */
const submitForm = () => {
  logisticsInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      let data = { ...form.value };
      if (form.value.chargeItem) {
        data.chargeItem = JSON.stringify(form.value.chargeItem);
        data.chargeItemHeaders = JSON.stringify(form.value.chargeItemHeaders);
        data.otherChargeItem = JSON.stringify(form.value.otherChargeItem);
      }
      if (form.value.logisticsInfoId) {
        await updateLogisticsInfo(data).finally(() => (buttonLoading.value = false));
      } else {
        await addLogisticsInfo(data).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: LogisticsInfoVO) => {
  const _logisticsInfoIds = row?.logisticsInfoId || ids.value;
  await proxy?.$modal.confirm('是否确认删除物流渠道编号为"' + _logisticsInfoIds + '"的数据项？').finally(() => (loading.value = false));
  await delLogisticsInfo(_logisticsInfoIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'oa/logisticsInfo/export',
    {
      ...queryParams.value
    },
    `logisticsInfo_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
